<template>
  <div class="loginWrapper">
    <div class="login-logo"></div>
    <div class="login-view">
      <div class="login-card">
        <div class="login-title">
          <p class="fz_25">登录</p>
          <p class="fz_15">轻备学院后台管理系统</p>
        </div>
        <div class="code-login" id="code-login" v-if="typeCode"></div>
        <div class="form-login" v-if="!typeCode">
          <el-form
            class="form"
            label-position="right"
            size="large"
            :model="form"
            ref="form"
            :rules="rules"
          >
            <el-form-item prop="username">
              <el-input
                prefix-icon="el-icon-user-solid"
                placeholder="输入登录用户名"
                v-model="form.username"
              />
            </el-form-item>
            <el-form-item prop="pwd">
              <el-input
                prefix-icon="el-icon-unlock"
                placeholder="输入用户密码"
                type="password"
                show-password
                v-model="form.pwd"
                class="pwd"
              />
            </el-form-item>
          </el-form>
          <div class="btn">
            <el-button type="success" class="login-btn" @click="submit" :loading="loading"
              >登录</el-button
            >
          </div>
        </div>
        <div class="login-type" @click="typeSwitch">
          切换至扫码登录
        </div>
      </div>
    </div>
    <div class="login-footer"></div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
// lib
// components & widgets
// config
import { APP_NAME } from "@/config/env";
// script
// controller & service & logic
import { createCopyRight } from "./logic";
import { loginService } from "@/biz/authorize/service";
import { getInfoMemberListService } from "@/biz/memberList/service";
import { getAdminRoleListService } from "@/biz/admin/service";
// interface
import { StoreState } from "@/store";
import logUtils from "@/utils/logUtils";
// 其它
import ddConfig from "@/config/dingding";

@Component
export default class Login extends Vue {
  appName = APP_NAME;
  copyright = createCopyRight();
  src = "";
  loading = false;
  form = {
    username: "",
    pwd: "",
  };
  rules = {
    username: [{ required: true, message: "请输入用户名，6到32位", min: 6, max: 32 }],
    pwd: [{ required: true, message: "请输入密码，6到32位", min: 6, max: 32 }],
  };
  typeCode = true; // true 扫码登录，false表单登录
  mounted() {
    this.init();
    // this.getCode();
  }
  init() {
    this.$store.commit("SET_ROUTERS", []); // 重置路由
    this.form.username = this.accountName; // 设置上一个登录的用户名
  }
  typeSwitch() {
    this.typeCode = !this.typeCode;
  }
  submit() {
    this.$router.push("/").catch(() => {
    // https://stackoverflow.com/questions/62223195/vue-router-uncaught-in-promise-error-redirected-from-login-to-via-a
    });
    // const form: any = this.$refs.form;
    // form.validate((valid: boolean) => {
    //   if (!valid) return;
    //   this.userLogin();
    // });
  }
  async userLogin() {
    this.loading = true;
    const result = await loginService(this.form.username, this.form.pwd, "");
    this.loading = false;
    if (result.payload) {
      this.$message.success(`用户 ${result.payload.username} 登录成功`);
      this.getMemberInfo(result.payload.id);
      this.getAdminRole(result.payload.id);
      // 路由跳转
      this.$router.push("/").catch(() => {
        // https://stackoverflow.com/questions/62223195/vue-router-uncaught-in-promise-error-redirected-from-login-to-via-a
      });
    }
  }
  get accountName() {
    const state: StoreState = this.$store.state;
    return state.account.account.username;
  }
  async getMemberInfo(sysUserID: string) {
    const result = await getInfoMemberListService({
      sysUserID,
    });

    if (result.payload) {
      this.$store.commit("SET_MEMBER_SYSUSERID", result.payload.memebersID);
    }
  }
  async getAdminRole(sysUserID: string) {
    const result = await getAdminRoleListService(sysUserID);

    if (result.payload) {
      const arr: any = result.payload;
      logUtils.log("role", result.payload);
      if (arr.length > 0) {
        for (let i = 0; i < arr.length; i += 1) {
          if (arr[i].sysRoleCode === "MEMBERADMIN") {
            this.$store.commit("SET_MEMBER_ISADMIN", true);
          }
        }
      } else {
        this.$store.commit("SET_MEMBER_ISADMIN", false);
      }
    }
  }
  getCode() {
    const goto = encodeURIComponent(`
    https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${ddConfig.dingAppid}
        &response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${ddConfig.dingRedirectUrl}
        
    `);
    // eslint-disable-next-line no-undef
    DDLogin({
      id: "code-login", // 这里需要你在自己的页面定义一个HTML标签并设置id
      goto, // 请参考注释里的方式
      style: "border:none;background-color:#FFFFFF;",
      width: "350",
      height: "350",
    });
    const handleMessage = (event: any) => {
      const origin = event.origin;
      if (origin === "https://login.dingtalk.com") {
        // 判断是否来自ddLogin扫码事件。

        window.location.href = `
         https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid= 
          ${ddConfig.dingAppid}
          &response_type=code&scope=snsapi_login&state=STATE&redirect_uri=http://dj52cm.natappfree.cc/ding/login&loginTmpCode= 
          ${event.data}
        `;
      }
    };
    if (typeof window.addEventListener !== "undefined") {
      window.addEventListener("message", handleMessage, false);
    } else if (typeof (window as any).attachEvent !== "undefined") {
      (window as any).attachEvent("onmessage", handleMessage);
    }
  }
}
</script>

<style lang="scss">
.loginWrapper {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
.login-logo {
  width: 120px;
  height: 26px;
  background-image: url("../../assets/logo.png");
  background-repeat: no-repeat;
  background-position: center;
  background-size: 100%;
  position: fixed;
  top: 30px;
  left: 100px;
}
.login-view {
  width: 100%;
  height: 100%;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-card {
  width: 350px;
  .form {
    box-shadow: 0 0 15px rgb(0 0 0 / 5%);
  }
  .code-login {
    width: 100%;
    height: 350px;
    background: #fff;
  }
  .form-login {
    height: 259px;
    padding-top: 60px;
    iframe{
      display: none;
    }
  }

  .el-card__body {
    padding: 20px 30px;
  }
  .el-form-item {
    margin: 0;
  }
  .el-input__inner {
    border: 0;
    border-radius: 0;
  }
  .pwd {
    border: 1px solid #f5f6fa;
  }
}
.login-title {
  // margin-bottom: 60px;
  p {
    text-align: center;
  }
  .fz_25 {
    font-size: 25px;
  }
  .fz_15 {
    font-size: 15px;
    margin-top: -10px;
  }
}
.btn {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 60px;
}
.login-btn {
  width: 100px;
  padding: 12px 0;
  font-size: 16px;
  // margin-top: 10px;
  // margin-bottom: 20px;
}
.login-type {
  text-align: center;
  margin-top: 20px;
  cursor: pointer;
  color: #666;
}
.login-footer {
  width: 405px;
  height: 14px;
  background-image: url("../../assets/foot.png");
  background-repeat: no-repeat;
  background-position: center;
  background-size: 100%;
  position: absolute;
  left: 50%;
  bottom: 50px;
  transform: translateX(-50%);
}
</style>
